﻿/*****************************************************************
*
*	Article:
*		How to register a system-wide hotkey in a win32 GUI application
*
*	Authors:
*		Miles Chen (stainboyx@hotmail.com)
*
*	Reference:
*		http://msdn.microsoft.com/en-us/library/ms646309(VS.85).aspx
*		http://msdn.microsoft.com/en-us/library/bb775233(VS.85).aspx
*
*	Build and Run:
*		cl /EHsc /Fosimple cpp-register-system-hotkey-win32.cpp & simple
*
*****************************************************************/
#ifndef UNICODE
#define UNICODE
#endif

#include <Windows.h>
#include <Commctrl.h>
#include <Shellapi.h>
#pragma comment(lib, "Kernel32.lib")
#pragma comment(lib, "User32.lib")
#pragma comment(lib, "Comctl32.lib")
#pragma comment(lib, "Shell32.lib")
#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#pragma comment(linker, "/ENTRY:__winmain")
#pragma comment(linker, "/SUBSYSTEM:WINDOWS")

#define WC_NAME L"My Applciation"
#define IDC_HOTKEY 1001
#define WM_HOTKEY_START	WM_USER + 100

// Global variables
long gHotkeyProc;

// Forward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);

int __winmain()
{
	// Ensure that the common control DLL is loaded. 
	InitCommonControls(); 

	MSG msg;
	HINSTANCE hInstance = GetModuleHandle(NULL);

	// Initialize global strings
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance, SW_SHOW))
	{
		return FALSE;
	}

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, NULL, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	ExitProcess(0);
	return (int) msg.wParam;
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage are only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(NULL, IDI_APPLICATION);
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= NULL;
	wcex.lpszClassName	= WC_NAME;
	wcex.hIconSm		= LoadIcon(NULL, IDI_APPLICATION);

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	HWND hWnd;

	hWnd = CreateWindow(WC_NAME, L"全局热键示例", WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

	if (!hWnd)
	{
		return FALSE;
	}

	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

	return TRUE;
}

//
//  FUNCTION: HotkeyWndProc(HWND, UINT, WPARAM, LPARAM)
//
LRESULT CALLBACK HotkeyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_SETFOCUS:
		// Disable hotkey
		UnregisterHotKey(GetParent(hWnd), WM_HOTKEY_START);
		break;
	case WM_KILLFOCUS:
		// Enable hotkey
		{
			// ref: http://msdn.microsoft.com/en-us/library/bb775235(VS.85).aspx
			WORD wKey = SendMessage(hWnd, HKM_GETHOTKEY, 0, 0);
			RegisterHotKey(GetParent(hWnd), WM_HOTKEY_START, HIBYTE(LOWORD(wKey)), LOBYTE(LOWORD(wKey)));
		}
		break;
	}
	return CallWindowProc((WNDPROC)gHotkeyProc, hWnd, message, wParam, lParam);
}


//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
	case WM_CREATE:
		{
			// Create a hotkey control whose ID=IDC_HOTKEY
			HWND hwndHot = CreateWindowEx(0,                   // no extended styles 
				HOTKEY_CLASS,             // class name 
				TEXT(""),                 // no title (caption) 
				WS_CHILD | WS_VISIBLE,    // style 
				15, 10,                   // position 
				200, 20,                  // size 
				hWnd,                     // parent window 
				(HMENU)IDC_HOTKEY,        // uses class menu 
				GetModuleHandle(NULL),    // instance 
				NULL);                    // no WM_CREATE 
			gHotkeyProc = SetWindowLongPtr(hwndHot, GWLP_WNDPROC, (LONG)HotkeyWndProc);
		}
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: Add any drawing code here...
		EndPaint(hWnd, &ps);
		break;
	case WM_DESTROY:
		// Delete hotkey control
		SendDlgItemMessage(hWnd, IDC_HOTKEY, WM_DESTROY, 0, 0);
		PostQuitMessage(0);
		break;
	case WM_HOTKEY:
		if(wParam == WM_HOTKEY_START)
		{
			// When hotkey is pressed, we simply launch an IE application and navigate it to Google China
			ShellExecute(hWnd, NULL, L"http://g.cn", NULL, NULL, SW_SHOW);
		}
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
